<!-- 显示我的课程，还差一个退课功能，还要把初始化id给去除 -->
<template>
  <div>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入要查询的课程名称" v-model="courseName">
            <el-button slot="append" icon="el-icon-search" @click="searchCourse">
            </el-button>
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-input placeholder="请输入要查询的课程ID" v-model="courseId">
            <el-button slot="append" icon="el-icon-search" @click="searchCourse">
            </el-button>
          </el-input>
        </el-col>
      </el-row>
      <el-table :data="tableData" border
          style="width: 100%">
      <el-table-column label="课程名称" width="170">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="课程号" width="170">
        <template slot-scope="scope">
          <span>{{ scope.row.courseId}}</span>
        </template>
      </el-table-column>
      <el-table-column label="学分" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.credit}}</span>
        </template>
      </el-table-column>
      <el-table-column label="时间" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.period }}</span>
        </template>
      </el-table-column>
      <el-table-column label="课程ID" width="240">
        <template slot-scope="scope">
          <span>{{ scope.row.collegeId }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="220">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleChoose(scope.$index, scope.row)"
            >选课</el-button>
        </template>
      </el-table-column>
    </el-table>
      <el-pagination
        :page-sizes="[1, 2, 3]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :total="firstFrom.total">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      firstFrom:{
        // 用于保存初始的条数
      total:0,
      },
      pageFrom:{
      page: 1,
      pageSize: 1,
      id:'',
      // 要传给后端的数据
      },
      // 用于成绩查询的检索
      courseName:'',
      courseId:'',
      total: 0,
      studentId:'',
      tableData: [
        // 表格数据
      ],
    }
  },
  methods: {
    handleCurrentChange(currentPage) {
      this.pageFrom.page = currentPage;
      // 每次更改都要请求一次tabledata数据，在后端做数据分页！>.<
      this.getOwnCourse();

    },
    handleSizeChange(size) {
      this.pageFrom.pageSize = size;
      // 每次更改都要请求一次tabledata数据，在后端做数据分页！>.<！
       this.getOwnCourse()
    },
    async getOwnCourse() {
    // JSON化
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'token':`${localStorage.getItem("token")}`
        // Custom request header
      }
    };
    try {
      const { data: res } = await this.$http.post(`api/admin/course/page`,JSON.stringify(this.pageFrom),config);
      if (res.status !== 500) {
        this.tableData=res.data.records;
      } else {
        this.$message.error('获取失败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('请求失败');
  }
},  
// 获取所有数据并保存
async getOwnFirstCourse() {
    // JSON化
    this.pageFrom.pageSize=10
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'token':`${localStorage.getItem("token")}`// Custom request header
      }
    };
    try {
      const { data: res } = await this.$http.post(`api/admin/course/page`,JSON.stringify(this.pageFrom),config);
      if (res.status !== 500) {
        this.$message.success('成功获取课程列表');
        this.tableData=res.data.records;
        this.firstFrom.total = res.data.total; // 保存总条数

      } else {
        this.$message.error('获取失败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('请求失败');
  }
},
//搜索功能
async searchCourse() {
      // 在这里执行你想要的点击事件的逻辑,
      const dataToSerialize = { ...this.pageFrom };

if (this.courseName) {
 dataToSerialize.courseName = this.courseName;
}

if (this.courseId) {
    dataToSerialize.courseId = this.courseId;
}
    // JSON化
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'token':`${localStorage.getItem("token")}`// Custom request header
      }
    };
    try {
      const { data: res } = await this.$http.post(`api/student/course/page`,JSON.stringify(dataToSerialize),config);
      if (res.status !== 500) {
        this.$message.success('成功查询');
        this.tableData=res.data.records;
        this.firstFrom.total = res.data.total;
      } else {
        this.$message.error('获取失败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('请求失败');
  }
},
handleChoose(index,row) {
      if (confirm("是否确认选取？")) {
        this.Choosecourse(row.courseId);
      }
    },
  
  async Choosecourse(data){
    const dataToSerialize ={};
if (this.pageFrom.id) {
 dataToSerialize.studentId = this.pageFrom.id;
}
dataToSerialize.courseId = data;
    // JSON化
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'token':`${localStorage.getItem("token")}`// Custom request header
      }
    };
    try {
      const { data: res } = await this.$http.post(`api/student/course/insert`,JSON.stringify(dataToSerialize),config);
      if (res.status !== 500) {
        this.$message.success('成功选课');
        this.getOwnFirstCourse();
      } else {
        this.$message.error('获取失败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('选课失败');
  }

  }
   
  },
  
  created() {
    // 初始化操作
    if(localStorage.getItem("type") !== 'student'){this.$router.push(`/login`);this.$message.error('你不是个学生');}
    this.name = localStorage.getItem('name');
    this.pageFrom.id=localStorage.getItem('studentId');
    this.getOwnFirstCourse();
  },
}
</script>